<?php
/**
 * 房源模型
 */

namespace app\admin\model;


use app\badmin\model\CompanyStatistics;
use app\common\lib\RespCode;
use app\common\model\BaseModel;
use custom\Err;
use custom\Redis;
use custom\TencentMap;
use house\HouseCount1;
use house\HouseCount3;
use oss\Oss;
use PDOStatement;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\Model;

class House extends BaseModel {

    /**
     * 列表字段
     * @var array
     */
    public static $h_column = ['h.is_shelf,h.title,h.id,h.build_area,h.floor,h.bedroom,h.area,h.cover,h.important,ha.source_type,ha.source_url'];
    public static $ha_column = ['ha.type,ha.auction_status,ha.start_time,ha.end_time,IF(ha.type=4,ha.pay_selloff,ha.initial_price) as initial_price,ha.discount'];
    public static $hv_column = ['hv.name as hv_name'];
    public static $ht_column = ['ht.name as ht_name'];

    const CONFIG_TYPE1 = 1;//价格
    const CONFIG_TYPE2 = 2;//面积
    const CONFIG_TYPE3 = 3;//折扣
    const CONFIG_TYPE4 = 4;//楼龄
    const CONFIG_TYPE5 = 5;//楼层

    //捡漏
    static $ha_type = [2, 3, 4, 5, 6];
    static $ha_astatus = [1, 2];

    static $whereList = [
        'a_type'          => [
            ['key' => 1, 'value' => '一拍'],
            ['key' => 2, 'value' => '二拍'],
            ['key' => 4, 'value' => '变卖'],
            ['key' => 5, 'value' => '重新拍卖'],
        ],
        'a_status'        => [
            ['key' => 1, 'value' => '待开始'],
            ['key' => 2, 'value' => '进行中'],
            ['key' => 3, 'value' => '已成交'],
            ['key' => 4, 'value' => '已流拍'],
            ['key' => 5, 'value' => '已撤回'],
            ['key' => 6, 'value' => '已终止'],
            ['key' => 7, 'value' => '已暂缓'],
        ],
        'other'           => [
            ['key' => 'hot', 'value' => '重点房源'],
            ['key' => 'today', 'value' => '即将开拍'],
            ['key' => 'pick_up', 'value' => '捡漏必看'],
            ['key' => 'best', 'value' => '品质豪宅'],
        ],
        'order'           => [
            ['key' => 1, 'value' => '默认排序'],
            ['key' => 2, 'value' => '按价格从高到低'],
            ['key' => 3, 'value' => '按价格从低到高'],
            ['key' => 4, 'value' => '按折扣从高到低'],
            ['key' => 5, 'value' => '按折扣从低到高'],
            ['key' => 6, 'value' => '开拍时间由远及近'],
            ['key' => 7, 'value' => '开拍时间由近及远'],
            ['key' => 8, 'value' => '最近发布'],
        ],
        'lifts'           => [
            ['key' => 1, 'value' => '电梯'],
            ['key' => 2, 'value' => '楼梯'],
            ['key' => 3, 'value' => '未知'],
        ],
        'bedroom'         => [
            ['key' => 1, 'value' => '一居室'],
            ['key' => 2, 'value' => '二居室'],
            ['key' => 3, 'value' => '三居室'],
            ['key' => 4, 'value' => '四居室'],
            ['key' => 5, 'value' => '五居室以上'],
        ],
        //        'bulu'            => [
        //            ['key' => 1, 'value' => '未补录'],
        //            ['key' => 2, 'value' => '已补录']
        //        ],
        'source_type'     => [
            ['key' => 1, 'value' => '京东网'],
            ['key' => 2, 'value' => '阿里网'],
            ['key' => 3, 'value' => '人民法院诉讼资产网'],
            ['key' => 4, 'value' => '中国拍卖行业协会网'],
            ['key' => 5, 'value' => '公拍网'],
            ['key' => 6, 'value' => '工行融e购'],
            ['key' => 7, 'value' => '北京产权交易所'],
        ],
        'living_type'     => [
            ['key' => 1, 'value' => '未知'],
            ['key' => 2, 'value' => '租赁'],
            ['key' => 3, 'value' => '空置'],
            ['key' => 4, 'value' => '有居住']
        ],
        'renovation_type' => [
            ['key' => 0, 'value' => '未知'],
            ['key' => 1, 'value' => '清水'],
            ['key' => 2, 'value' => '简装'],
            ['key' => 3, 'value' => '中装'],
            ['key' => 4, 'value' => '精装'],
        ],
        'property_type'   => [
            ['key' => 1, 'value' => '未知'],
            ['key' => 2, 'value' => '产权房'],
            ['key' => 3, 'value' => '合同房'],
            ['key' => 4, 'value' => '房改房'],
            ['key' => 5, 'value' => '安置房'],
            ['key' => 6, 'value' => '福利房'],
            ['key' => 7, 'value' => '廉租房'],
        ],
        'house_cate'      => [
            ['key' => 0, 'value' => '普通'],
            ['key' => 1, 'value' => '跃层'],
            ['key' => 2, 'value' => '别墅'],
        ]
    ];

    //楼梯
    const ELEVVATORS = [
        0 => '- -',
        1 => '电梯',
        2 => '楼梯',
        3 => '未知',
    ];

    //拍卖阶段映射
    const A_TYPES = [
        0 => '未知',
        1 => '一拍',
        2 => '二拍',
        3 => '三拍',
        4 => '变卖',
        5 => '重新拍卖',
        6 => '破产',
    ];

    //拍卖状态映射
    const A_STATUSS = [
        0 => '未知',
        1 => '待开始',
        2 => '进行中',
        3 => '已成交',
        4 => '已流拍',
        5 => '已撤回',
        6 => '已终止',
        7 => '已暂缓',
    ];

    //户型映射
    const BED_ROOM_COMFIG = [
        0 => '',
        1 => '一居室',
        2 => '二居室',
        3 => '三居室',
        4 => '四居室',
    ];

    //映射装修
    const RENOVATION_TYPE = [
        0 => '- -',
        1 => '清水',
        2 => '简装',
        3 => '中装',
        4 => '精装',
    ];

    /**
     * 房源列表
     * @param $params
     * @param $data_
     * @param $page_
     * @param $pageNum_
     * @param $count_
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function getList($params, &$data, &$page, &$pageNum, &$count) {
        $column = array_merge(self::$h_column, self::$ha_column, self::$hv_column, self::$ht_column);
        list($map, $whereRaw, $order) = static::listWhere($params);
        self::getDatas($map, $whereRaw, $column, $order, (int)$params['page'], $params['long'], $data, $page, $pageNum, $count);
    }

    /**
     * 获取导出数据
     * @param $params
     * @param $column
     * @param $data
     * @param $page
     * @param $pageNum
     * @param $count
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function exportData($params) {
        $field = $params['field'];
        $field = explode(',', $field);
        $all_field = config('export.export_db_field');
        if (!in_array('id', $field)) {
            array_unshift($field, 'id');
        }

        $db_field = array_flip($field);
        foreach ($all_field as $key => $value) {
            if (isset($db_field[$key])) {
                $column[] = $value;
            }
        }
        list($map, $whereRaw, $order) = static::listWhere($params);
        $data = self::getExportDatas($map, $whereRaw, $column, $order);
        if (!$data) {
            Err::add('没有符合条件的数据', RespCode::DATA_ERR);
            return false;
        } else {
            $data = self::hanldReturnDwnlaod($data, $field);
            $hed = config('export.export_field_name');
            $tit_field = array_flip($field);
            foreach ($hed as $key => $value) {
                if (isset($tit_field[$key]))
                    $title[] = $value;
            }
            $arr = array('data' => $data, 'title' => $title);
            $redisModel = Redis::getInstance();
            $key = $params['user_id'] . time();
            $timeout = 60 * 5;//过期时间
            if (!$redisModel->setex($key, $timeout, json_encode($arr))) {
                Err::add('导出失败');
                return false;
            }
            return $key;
        }
    }

    /**
     * 列表查询条件
     * @param $params
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    protected static function listWhere($params) {
        $map = [];
        $map[] = ['h.deleted', '=', 0];
        $whereRaw = '1';
        //全部房源
        if ($params['type'] == 1) {
            $map[] = ['h.is_shelf', '=', 1];
            $map[] = ['h.is_update', '=', 1];
        }
        //待补录
        if ($params['type'] == 2) {
            $map[] = ['h.is_update', '=', 0];
            $map[] = ['h.is_shelf', '=', 0];
        }
        //下架房源
        if ($params['type'] == 3) {
            $map[] = ['h.is_update', '=', 1];
            $map[] = ['h.is_shelf', '=', 0];
        }
        //纠错房源
        if ($params['type'] == 4) {
            $map[] = ['h.is_update', '=', 1];
            $whereRaw .= ' and ';
            $whereRaw .= "(" . Db::name('house_err')
                    ->where('house_id', 'h.id')
                    ->where('status', 0)
                    ->fetchSql(true)
                    ->count() . ") > 0";
        }
        //城市
        $city_code = $params['city_code'];
        $region_data = Db::name('region')->where('city_code', $city_code)->find();
        $codes = $region_data['p_codes'] . $city_code . ',';
        $map[] = ['h.city_codes', 'like', trim($codes) . '%'];

        //时间
        if (!empty($params['start_time']) && !empty($params['end_time'])) {
            $map[] = ['ha.start_time', '>=', strtotime(date('Y-m-d', strtotime($params['start_time'])) . '00:00:01')];
            $map[] = ['ha.start_time', '<=', strtotime(date('Y-m-d', strtotime($params['end_time'])) . '23:59:59')];
        }

        //区域
        if (!empty($params['area'])) {
            $map[] = ['h.city_code', '=', $params['area']];
        }

        //面积
        if (!empty($params['build_area'])) {
            $map[] = createSectionQuery1($params['build_area'], 'h.build_area');
        }

        //起拍价
        if (!empty($params['initial_price'])) {
            $map[] = createSectionQuery1($params['initial_price'], 'ha.initial_price');
        }

        //阶段
        if (!empty($params['a_type'])) {
            $map[] = ['ha.type', 'in', $params['a_type']];
        }

        //拍卖状态
        if (!empty($params['a_status'])) {
            $map[] = ['ha.auction_status', 'in', $params['a_status']];
        }

        //户型
        if (!empty($params['bedroom'])) {
            $bedroom = explode(',', $params['bedroom']);
            if (isset($bedroom[1])) {
                if (in_array(5, $bedroom)) {
                    $bedmap[0] = 'h.bedroom';
                    $bedmap[1][] = ['>=', 5];
                    $bedmap[1][] = ['in', $bedroom];
                    $bedmap[2] = 'or';
                } else {
                    $bedmap[] = ['h.bedroom', 'in', $bedroom];
                }
                $map[] = $bedmap;
            } else {
                if ($params['bedroom'] < 5) {
                    $map[] = ['h.bedroom', 'in', $bedroom];
                } else {
                    $map[] = ['h.bedroom', '>=', $params['bedroom']];
                }
            }
        }

        //折扣比
        if (!empty($params['discount'])) {
            $whereRaw .= " and ";
            $whereRaw .= '( ' . createSectionDiscount($params['discount'], 'ha.discount') . ' )';
        }

        //楼层
        if (!empty($params['house_floor'])) {
            $map[] = createSectionQuery1($params['house_floor'], 'h.floor');
        }

        //来源
        if (!empty($params['source_type'])) {
            $map[] = ['h.source_type', 'in', $params['source_type']];
        }

        //房源类型
        if (!empty($params['house_type'])) {
            $map[] = ['h.house_type_id', 'in', $params['house_type']];
        }

        // 其他
        if (!empty($params['other'])) {
            $villa_config = Db::name('villa')->where("city_code", $city_code)->field('price')->find();
            if (!empty($villa_config['pirce'])) {
                $_best = ['initial_price', '>=', $villa_config['pirce']];
            } else {
                $_best = ['initial_price', '>=', 500000000];
            }

            $otherMap = [
                'hot'     => [
                    ['h.important', '=', 1],//重点
                    ['ha.auction_status', '=', 1]//待开始
                ],
                'today'   => [
                    ['ha.start_time', '>=', strtotime(date('Y-m-d', time()))],
                    ['ha.start_time', '<', strtotime(date('Y-m-d', strtotime('5 day')))],
                    ['ha.auction_status', '=', 1],
                ],
                'pick_up' => [
                    ['ha.type', 'in', self::$ha_type],//非一拍
                    ['ha.auction_status', 'in', self::$ha_astatus]//待开始，进行中
                ],
                'best'    => [
                    ['ha.auction_status', 'in', self::$ha_astatus],//待开始，进行中
                    $_best
                ]
            ];

            $other = explode(',', $params['other']);
            foreach ($other as $j => $k) {
                $map[] = $otherMap[$k];
            }
        }

        //房源标题或小区标题
        if (!empty($params['h_title'])) {
            $map[] = ['h.title|hv.name', 'like', '%' . trim($params['h_title']) . '%'];
        }

        //排序
        $order = house_order($params['order'] ?? '');

        !isset($params['page']) ? $params['page'] = 1 : $params['page'];
        !isset($params['long']) ? $params['long'] = 12 : $params['long'];

        $map[] = ['ha.type', 'in', [0, 1, 2, 3, 4, 5, 6]];//避免出现没有拍卖数据的房源
        return [$map, $whereRaw, $order];
    }

    /**
     * 筛选多条数据
     * @param $map
     * @param $column
     * @param $order
     * @param $start
     * @param $long
     * @param $data
     * @param $page
     * @param $pageNum
     * @param $count
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function getDatas($map, $whereRaw, $column, $order, $start, $long, &$data, &$page, &$pageNum, &$count) {
        $data = db('house')
            ->alias('h')
            ->leftJoin('house_village hv', 'hv.id=h.village_id')
            ->leftJoin('house_auction ha', 'ha.id=h.auction_id')
            ->leftJoin('house_type ht', 'ht.id=h.house_type_id')
            ->where($map);
        if ($whereRaw) {
            $data->whereRaw($whereRaw);
        }
        $data = $data->order($order)
            ->page($start, $long)
            ->field($column)
            ->fieldRaw("(" . Db::name('house_err')->where('status', 0)->where('house_id', 'h.id')->fetchSql(true)->count() . ") as err_num")
            ->select();

        $count = db('house')
            ->alias('h')
            ->leftJoin('house_village hv', 'hv.id=h.village_id')
            ->leftJoin('house_auction ha', 'ha.id=h.auction_id')
            ->leftJoin('house_type ht', 'ht.id=h.house_type_id')
            ->where($map);
        if ($whereRaw) {
            $count->whereRaw($whereRaw);
        }
        $count = $count->count();
        foreach ($data as $k => $v) {
            $data[$k]['initial_price'] = deal_data_info($v['initial_price'], 6);
            $data[$k]['type'] = self::A_TYPES[$v['type']];
            $data[$k]['auction_status'] = self::A_STATUSS[$v['auction_status']];
            $data[$k]['start_time'] = empty($data[$k]['start_time']) ? '' : date('Y/m/d H:i:s', $v['start_time']);
            $data[$k]['end_time'] = empty($data[$k]['end_time']) ? '' : date('Y/m/d H:i:s', $v['end_time']);
            $data[$k]['hv_name'] = empty($data[$k]['hv_name']) ? '' : $data[$k]['hv_name'];
            $data[$k]['build_area'] = empty($data[$k]['build_area']) ? '' : deal_area_list($data[$k]['build_area'], 4) . '㎡';
            if ($data[$k]['discount'] <= 1 && $data[$k]['discount'] != -1) {
                $data[$k]['discount'] = '低于1折';
            } elseif ($data[$k]['discount'] == -1) {
                $data[$k]['discount'] = '- -';
            } else {
                $data[$k]['discount'] = $v['discount'];
            }
            if ($data[$k]['bedroom'] >= 5) {
                $data[$k]['bedroom'] = '五居室以上';
            } else {
                $data[$k]['bedroom'] = self::BED_ROOM_COMFIG[$data[$k]['bedroom']];
            }
            if ($data[$k]['floor']) {
                $data[$k]['floor'] = $data[$k]['floor'] . '楼';
            } else {
                $data[$k]['floor'] = '';
            }

            $sourceList = House::$whereList['source_type'];
            foreach ($sourceList as $arr => $item)
                $sourceList[$arr]['key'] == $data[$k]['source_type'] && $data[$k]['source_type'] = $sourceList[$arr]['value'];

            $data[$k]['ht_name'] = $data[$k]['ht_name'] ?? '';
        }
        $page = $start;
        if ($long > 0) {
            $pageNum = ceil($count / $long);
        } else {
            $pageNum = 1;
        }
    }

    /**
     * 房源详情
     * @param $params
     * @return array|PDOStatement|string|Model|null
     * @throws Exception
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function houseInfo($params) {
        $data = db("house")
            ->alias('h')
            ->leftJoin('house_village hv', 'hv.id=h.village_id')
            ->leftJoin('house_auction ha', 'ha.id=h.auction_id')
            ->leftJoin('house_type ht', 'ht.id=h.house_type_id')
            ->field('h.title,ht.name as htname,h.address,h.city_codes,h.build_area,h.bedroom,h.floor,h.build_time,h.lifts,ha.discount,h.cover,ha.id as action_id,h.business_area_id,h.village_id,h.pic,x(hv.location) as lng,Y(hv.location) as lat,h.livingroom,h.renovation_type,h.province,h.city,h.area,hv.name as hv_name,IF(ha.type=4,ha.pay_selloff,ha.initial_price) as initial_price,ha.consult_price,ha.market_price,h.is_shelf')
            ->fieldRaw("(" . Db::name('house_err')->where('status', 0)->where('house_id', 'h.id')->fetchSql(true)->count() . ") as err_num")
            ->where('h.deleted', 0)
            ->find($params['id']);
        if (empty($data)) {
            Err::add('数据不存在', RespCode::PARAMS_ERR);
            return false;
        }
        $address_detail = $data['province'] . '-' . $data['city'] . '-' . $data['area'];
        $rank = substr($data['city_codes'], 1, strlen($data['city_codes']) - 2);
        unset($data['province']);
        unset($data['city']);
        unset($data['area']);

        if (!empty($data['business_area_id'])) {
            $BusinessArea = BusinessArea::getOne([['id', '=', $data['business_area_id']]], 'name,city_id');
            $address_detail .= '-' . $BusinessArea['name'];
            $rank .= ',' . $data['business_area_id'];
        }
        if (!empty($data['village_id'])) {
            $village = HouseVillage::getOne([['id', '=', $data['village_id']]], 'name,city_code');
            $address_detail .= '-' . $village['name'];
            $rank .= ',' . $data['village_id'];
        }
        $data['ranks'] = $rank;
        $data['address_detail'] = $address_detail;
        $data['cover'] = empty($data['cover']) ? config('global.empty_house_img') : $data['cover'];
        unset($data['city_codes']);
        unset($data['district']);
        unset($data['business_area_id']);
        $data['pic'] = empty($data['pic']) ? [] : explode(',', $data['pic']);
        $data['lifts'] = self::ELEVVATORS[$data['lifts']];
        $data['renovation_type'] = self::RENOVATION_TYPE[$data['renovation_type']];
        $data['build_area'] = empty($data['build_area']) ? '- -' : deal_data_info($data['build_area'], 4) . '㎡';
        $data['build_time'] = empty($data['build_time']) ? '- -' : $data['build_time'];
//        $data['discount'] = $data['discount'] <= 1 ? '低于1折' : (string)$data['discount'] . '折';
        if ($data['discount'] <= 1 && $data['discount'] != -1) {
            $data['discount'] = '低于1折';
        } elseif ($data['discount'] == -1) {
            $data['discount'] = '- -';
        } else {
            $data['discount'] = (string)$data['discount'] . '折';
        }
        deal_money_info($data['initial_price'], $initial_price, $initial_price_unit);
        $data['initial_price'] = $initial_price . $initial_price_unit;
        deal_money_info($data['consult_price'], $consult_price, $consult_price_unit);
        $data['consult_price'] = $consult_price . $consult_price_unit;
        deal_money_info($data['market_price'], $market_price, $market_price_unit);
        $data['market_price'] = $market_price . $market_price_unit;
        $data['room'] = empty($data['bedroom']) || empty($data['livingroom']) ? '- -' : $data['bedroom'] . '室' . $data['livingroom'] . '厅';
        unset($data['livingroom']);
        unset($data['bedroom']);
        $data['floor'] = empty($data['floor']) ? '- -' : $data['floor'] . '楼';
        $data['hv_name'] = empty($data['hv_name']) ? '' : $data['hv_name'];
        $data['lng'] = empty($data['lng']) ? '' : $data['lng'];
        $data['lat'] = empty($data['lat']) ? '' : $data['lat'];
        return $data;
    }

    /**
     * 上下架
     * @param $id
     * @return bool
     * @throws Exception
     * @throws PDOException
     */
    public static function edit_is_shelf($params, &$msg = '') {
        $ids = explode(',', $params['ids']);
        $houseModel = new self();
        if ($params['type'] == 1) {//批量上架
            $count1 = db("house")
                ->alias('h')
                ->leftJoin('house_auction ha', 'ha.id=h.auction_id')
                ->where('h.id', 'in', $ids)
                ->where('ha.type', 'null')
                ->count();
            if ($count1 > 0) $msg = '未绑定拍卖信息的房源未能成功上架，失败：' . $count1 . '套';

            $count2 = db("house")
                ->where('id', 'in', $ids)
                ->where('deleted', 1)
                ->count();
            if ($count2 > 0) $msg = '不存在的房源未能成功上架，失败：' . $count2 . '套';

            $count3 = db("house")
                ->where('id', 'in', $ids)
                ->where('is_update', 0)
                ->count();
            if ($count3 > 0) $msg = '未补录的房源未能成功上架，失败：' . $count3 . '套';

            $count4 = db("house")
                ->where('id', 'in', $ids)
                ->where('village_id', 0)
                ->count();
            if ($count4 > 0) $msg = '未绑定小区的房源未能成功上架，失败：' . $count4 . '套';

            Db::startTrans();
            $houseCount3 = new HouseCount3($params['type'], $ids);
            $house = $houseCount3->getContent();
            if ($house) {
                if (!isset($msg)) $msg = '上架成功';
            } else {
                $msg = '上架失败,未绑定小区/错误的拍卖信息';
                Err::add($msg, RespCode::PARAMS_ERR);
                return false;
            }
        } //批量下架
        else {
            Db::startTrans();
            $msg = '下架成功';
            $houseCount3 = new HouseCount3($params['type'], $ids);
            $house = $houseCount3->getContent();
        }
        if ($house) {
            $idArr = array_column($house, 'id');
            foreach ($idArr as $v) {
                $arr = [
                    'id'       => $v,
                    'is_shelf' => $params['type'] == 1 ? 1 : 0,
                ];
                if ($params['type'] == 1) {
                    $arr['on_time'] = time();
                } else {
                    $arr['off_time'] = time();
                }
                $list[] = $arr;
            }
            $houseModel->saveAll($list);
        }
        Db::commit();
        return true;
    }

    /**
     * 删除
     * @param $id
     * @return bool
     * @throws Exception
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws PDOException
     */
    public static function del($id) {
        $getOne = db('house')
            ->where('id', $id)
            ->where('deleted', 0)
            ->find();
        if (empty($getOne)) {
            Err::add('数据不存在');
            return false;
        }
        if ($getOne['is_shelf'] == 1) {
            Err::add('请先下架');
            return false;
        }
        db("house")->where('id', $id)->update(['deleted' => 1]);
        return true;
    }

    /**
     * 筛选单条
     * @param array|null $map
     * @param $column
     * @return array|PDOStatement|string|Model|null
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function getOne(?array $map, $column) {
        return Db::name("house")
            ->where($map)
            ->field($column)
            ->find();
    }

    /**
     * 验证参数
     * @param $params
     * @return bool
     */
    public static function checkParams(&$params) {
        if (mb_strlen(trim($params['address']), 'utf-8') > 100) {
            Err::add('地址长度限制100', RespCode::QUERY_ERR);
            return false;
        }

        if (!is_numeric($params['build_area']) || $params['build_area'] <= 0 || $params['build_area'] > 99999) {
            Err::add('错误的建筑面积,取值范围1-99999', RespCode::QUERY_ERR);
            return false;
        }
        if (!empty($params['floor'])) {
            if (!is_numeric($params['floor']) || $params['floor'] <= 0 || $params['floor'] > 99999) {
                Err::add('错误的楼层1-99999', RespCode::QUERY_ERR);
                return false;
            }
        }
        if (!empty($params['anjuke_url'])) {
            if (mb_strlen(trim($params['anjuke_url']), 'utf-8') > 100) {
                Err::add('安居客地址长度超过100', RespCode::QUERY_ERR);
                return false;
            }
        }
        if (!empty($params['anjuke_price'])) {
            if (preg_match('/^[1-9]{1}\d{0,5}$/', $params['anjuke_price']) == false) {
                Err::add('安居客价格请输入1-999999的整数', RespCode::PARAMS_ERR);
                return false;
            }
        }
        if (!empty($params['build_time'])) {
            if (!filter_var($params['build_time'], FILTER_VALIDATE_INT, ["options" => ["min_range" => 1980, "max_range" => 2200]])) {
                Err::add('错误的建筑年代', RespCode::QUERY_ERR);
                return false;
            }
        }
        if (count(explode(',', $params['pic'])) > 10) {
            Err::add('缩略图最多10张', RespCode::QUERY_ERR);
            return false;
        }
        $int_options = array(
            "options" => array(
                "min_range" => 0,
                "max_range" => 50
            )
        );
        if (!empty($params['bedroom'])) {
            if (!filter_var($params['bedroom'], FILTER_VALIDATE_INT, $int_options)) {
                Err::add('户型错误', RespCode::QUERY_ERR);
                return false;
            }
        }
        if (!empty($params['livingroom'])) {
            if (!filter_var($params['livingroom'], FILTER_VALIDATE_INT, $int_options)) {
                Err::add('户型错误', RespCode::QUERY_ERR);
                return false;
            }
        }
        if (!empty(trim($params['warrant']))) {
            if (mb_strlen(trim($params['warrant']), 'utf-8') > 50) {
                Err::add('权证号长度超过50', RespCode::QUERY_ERR);
                return false;
            }
        }
        return true;
    }

    /**
     * 修改房源补录信息
     * @param $params
     * @return bool
     * @throws Exception
     * @throws PDOException
     */
    public static function editinfo($params, &$msg) {
        $old = Db::name('house')
            ->where('id', $params['id'])
            ->find();
        if ($old['deleted'] == 1) {
            Err::add('房源不存在', RespCode::QUERY_ERR);
            return false;
        }
        if (!self::checkParams($params)) {
            return false;
        }

        $region_data = Region::getOne([['city_code', '=', $params['city_code']]], '*');
        $p_code = $region_data['p_code'];
        $city_codes = ',' . $p_code . ',' . $params['city_code'] . ',' . $params['area_code'] . ',';

        $lat = $params['lat'] ?? 0;
        $lng = $params['lng'] ?? 0;

        $v_id = $params['v_id'] ?? 0;
        $b_id = $params['b_id'] ?? 0;
        if ($v_id !== 0 && empty(db('house_village')
                ->where("id", $v_id)
                ->where('city_codes', $city_codes)
                ->select())) {
            Err::add('小区参数错误', RespCode::QUERY_ERR);
            return false;
        }

        if ($b_id !== 0 && empty(db('business_area')
                ->where("id", $b_id)
                ->where('city_ids', $city_codes)
                ->select())) {
            Err::add('商圈参数错误', RespCode::QUERY_ERR);
            return false;
        }

        $update = [
            'village_id'       => $v_id,
            'business_area_id' => $b_id,
            'city'             => Region::getOne([['city_code', '=', $params['city_code']]], 'name')['name'],
            'area'             => Region::getOne([['city_code', '=', $params['area_code']]], 'name')['name'],
            'city_code'        => $params['area_code'],
            'city_codes'       => $city_codes,
            'address'          => $params['address'],
            'floor'            => $params['floor'] ?? 0,
            'livingroom'       => $params['livingroom'] ?? 0,
            'bedroom'          => $params['bedroom'] ?? 0,
            'build_time'       => $params['build_time'] ?? 0,
            'build_area'       => $params['build_area'] * 10000,
            'house_type_id'    => $params['house_type'],
            'house_cate'       => $params['house_cate'] ?? 0,
            'living_type'      => $params['living_type'],
            'renovation_type'  => $params['renovation_type'],
            'property_type'    => $params['property_type'] ?? 0,
            'warrant'          => $params['warrant'] ?? '',
            'utime'            => time(),
            'is_update'        => 1,
            'location'         => Db::raw("POINT('{$lng}', '{$lat}')"),
            'lat'              => $lat,
            'lng'              => $lng,
            'lifts'            => $params['lifts'],
            'anjuke_url'       => $params['anjuke_url'] ?? '',
            'anjuke_price'     => empty($params['anjuke_price']) ? 0 : $params['anjuke_price'] * 100,
            'pic'              => $params['pic'],
            'cover'            => explode(',', $params['pic'])[0],
            'bulu_time'        => strtotime(date('Y-m-d', time())),

        ];
        //删除图片
        $removePic = array_diff(explode(',', $old['pic']), explode(',', $params['pic']));
        $oss = Oss::getInstance();
        foreach ($removePic as $value) {
            if (substr($value, 0, 23) == Oss::$config['domain']) {
                $oss->delOneFile($value);
            }
        }
        //修改之前是未补录
        if (Db::name('house')
                ->where('id', $params['id'])->value('is_update') == 0) {
            $msg = '房源已被保存到下架房源中';
        } else {
            $msg = '编辑成功';
        }
        //房源数变化
        $houseCount1 = new HouseCount1();
        $houseCount1($params['id'], $update);

        Db::name('house')
            ->where('id', $params['id'])
            ->update($update);
        return true;
    }

    /**
     * 区间数据
     * @param $city_code
     * @return mixed
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function allIntervel($city_code) {
        $interval_config = Db::name('interval_config')
            ->order('min', 'asc')
            ->whereOr('city_code', 0)
            ->whereOr('city_code', $city_code)
            ->field('type,name as value,min,max')
            ->select();
        $i = 0;
        do {
            if ($interval_config[$i]['type'] == self::CONFIG_TYPE1) {
                $all_intervel['price_interval'][] = self::deal($interval_config[$i]);
            }
            if ($interval_config[$i]['type'] == self::CONFIG_TYPE2) {
                $all_intervel['build_area_interval'][] = self::deal($interval_config[$i]);
            }
            if ($interval_config[$i]['type'] == self::CONFIG_TYPE3) {
                $all_intervel['discount_interval'][] = self::deal($interval_config[$i]);
            }
            if ($interval_config[$i]['type'] == self::CONFIG_TYPE4) {
                $all_intervel['house_age'][] = self::deal($interval_config[$i]);
            }
            if ($interval_config[$i]['type'] == self::CONFIG_TYPE5) {
                $all_intervel['house_floor'][] = self::deal($interval_config[$i]);
            }
            $i++;
        } while ($i < count($interval_config));
        return $all_intervel;
    }

    /**
     * 区间处理
     * @param $arr
     * @return mixed
     */
    public static function deal($arr) {
        $arr['key'] = $arr['min'] . '-' . $arr['max'];
        unset($arr['min']);
        unset($arr['max']);
        unset($arr['type']);
        return $arr;
    }

    /**
     * 编辑补录获取详情
     * @param $params
     * @return array|PDOStatement|string|Model|null
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function editInfoGet($params) {
        $data = db("House")
            ->alias('h')
            ->leftJoin('house_village hv', 'hv.id=h.village_id')
            ->leftJoin('business_area ba', 'h.business_area_id=ba.id')
            ->where('h.id', $params['id'])
            ->where('h.deleted', 0)
            ->field('hv.name as hv_name,h.city,h.area,ba.name as ba_name,h.address,x(hv.location) as lng,Y(hv.location) as lat,house_type_id as house_type,h.house_cate,h.build_area,h.livingroom,h.bedroom,h.anjuke_url,h.floor,h.anjuke_price,h.build_time,h.lifts,h.living_type,h.renovation_type,h.warrant,h.property_type,pic,h.village_id as v_id,h.is_shelf')
            ->find();
        if (empty($data)) {
            Err::add('房源不存在', RespCode::PARAMS_ERR);
            return false;
        }
        $data['hv_name'] = empty($data['hv_name']) ? '' : $data['hv_name'];
        $data['build_area'] = $data['build_area'] > 0 ? deal_data_info($data['build_area'], 4) : '';
        $data['livingroom'] = $data['livingroom'] > 0 ? $data['livingroom'] : '';
        $data['bedroom'] = $data['bedroom'] > 0 ? $data['bedroom'] : '';
        $data['floor'] = $data['floor'] > 0 ? $data['floor'] : '';
        $data['anjuke_price'] = !empty($data['anjuke_price']) ? $data['anjuke_price'] / 100 : '';
        $data['build_time'] = !empty($data['build_time']) ? $data['build_time'] : '';
        $data['warrant'] = !empty($data['warrant']) ? $data['warrant'] : '';
        $data['lng'] = !empty($data['lng']) ? $data['lng'] : '';
        $data['lat'] = !empty($data['lat']) ? $data['lat'] : '';
        return $data;
    }

    /**
     * 添加房源
     * @param $params
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     * @throws PDOException
     */
    public static function addHouse($params) {
        if (!self::checkParams($params) || !HouseAuction::checkParams($params)) return false;

        $params = price_arr_deal($params, 1);
        $params['title'] = trim($params['title']);
        if (mb_strlen($params['title'], 'utf-8') > 100) {
            Err::add('房源标题长度超过100', RespCode::QUERY_ERR);
            return false;
        }
        if (db('house')->where('title', $params['title'])->find()) {
            Err::add('房源已存在', RespCode::QUERY_ERR);
            return false;
        }
        $region_data = Region::getOne([['city_code', '=', $params['city_code']]], '*');
        $p_code = $region_data['p_code'];
        $city_codes = ',' . $p_code . ',' . $params['city_code'] . ',' . $params['area_code'] . ',';

        $discount = -1;
        if (!empty($params['market_price'])) {
            // 当初始价 小于等于市场价时，才计算折扣
            if ($params['initial_price'] < $params['market_price']) {
                $discount = round($params['initial_price'] / $params['market_price'] * 10, 2);
                $discount < 1 && $discount = 0;
                $discount >= 10 && $discount = 10;
            }
        }

        $lng = $params['lng'] ?? 0;
        $lat = $params['lat'] ?? 0;

        $v_id = $params['v_id'] ?? 0;
        $b_id = $params['b_id'] ?? 0;
        if ($v_id !== 0 && empty(db('house_village')
                ->where("id", $v_id)
                ->where('city_codes', $city_codes)
                ->select())) {
            Err::add('小区参数错误', RespCode::QUERY_ERR);
            return false;
        }

        if ($b_id !== 0 && empty(db('business_area')
                ->where("id", $b_id)
                ->where('city_ids', $city_codes)
                ->select())) {
            Err::add('商圈参数错误', RespCode::QUERY_ERR);
            return false;
        }

        Db::startTrans();
        $HouseData = [
            'village_id'       => $v_id,
            'business_area_id' => $b_id,
            'auction_id'       => 0,
            'source_type'      => $params['source_type'],
            'source_url'       => $params['source_url'],
            'anjuke_url'       => $params['anjuke_url'] ?? '',
            'title'            => $params['title'],
            'sn'               => md5($params['title']),
            'cover'            => explode(',', $params['pic'])[0],
            'province'         => Region::getOne([['city_code', '=', $p_code]], 'name')['name'],
            'city'             => Region::getOne([['city_code', '=', $params['city_code']]], 'name')['name'],
            'area'             => Region::getOne([['city_code', '=', $params['area_code']]], 'name')['name'],
            'city_code'        => $params['area_code'],
            'city_codes'       => $city_codes,
            'address'          => $params['address'],
            'map_address'      => '',
            'district'         => '',
            'floor'            => $params['floor'] ?? 0,
            'max_floor'        => 0,
            'bedroom'          => $params['bedroom'] ?? 0,
            'livingroom'       => $params['livingroom'] ?? 0,
            'build_time'       => $params['build_time'] ?? 0,
            'build_area'       => $params['build_area'] * 10000,
            'renovation_type'  => $params['renovation_type'],
            'house_type_id'    => $params['house_type'],
            'house_type_ids'   => '',
            'house_cate'       => $params['house_cate'] ?? 0,
            'living_type'      => $params['living_type'],
            'lease_remark'     => '',
            'property_type'    => $params['property_type'] ?? 0,
            'warrant'          => $params['warrant'] ?? '',
            'anjuke_price'     => empty($params['anjuke_price']) ? 0 : $params['anjuke_price'],
            'itime'            => time(),
            'utime'            => time(),
            'source_utime'     => 0,
            'staff_id'         => 0,
            'important'        => 0,
            'is_shelf'         => 0,
            'deleted'          => 0,
            'is_update'        => 1,
            'is_complete'      => 0,
            'customer_count'   => 0,
            'lifts'            => $params['lifts'],
            'pic'              => $params['pic'],
            'lng'              => $lng,
            'lat'              => $lat,
            'location'         => Db::raw("POINT('{$lng}', '{$lat}')"),
            'from'             => 2,
            'bulu_time'        => strtotime(date('Y-m-d', time())),
            'market_price'     => $params['market_price'] ?? 0,

        ];
        $house_id = Db::name('house')->insertGetId($HouseData);
        if (!$house_id) {
            Db::rollback();
            Err::add('添加失败', RespCode::QUERY_ERR);
            return false;
        }
        $aucData = [
            'house_id'           => $house_id,
            'source_id'          => $params['source_id'],
            'source_type'        => $params['source_type'],
            'court_name'         => $params['court_name'],
            'start_time'         => strtotime($params['start_time']),
            'end_time'           => strtotime($params['end_time']),
            'institution'        => $params['court_name'] ?? '',
            'contact_name'       => $params['contact_name'] ?? '',
            'contact_tel'        => $params['contact_tel'] ?? '',
            'initial_price'      => $params['initial_price'],
            'consult_price'      => empty($params['consult_price']) ? 0 : $params['consult_price'],
            'bond'               => empty($params['bond']) ? 0 : $params['bond'],
            'market_price'       => empty($params['market_price']) ? 0 : $params['market_price'],
            'pay_selloff'        => $params['type'] == 4 ? $params['initial_price'] : 0,
            'discount'           => $discount,
            'type'               => $params['type'],
            'predict_price'      => 0,
            'price_lower_offset' => $params['price_lower_offset'],
            'final_price'        => 0,
            'tail_money_date'    => empty($params['tail_money_date']) ? '' : $params['tail_money_date'],
            'enroll_num'         => $params['enroll_num'] ?? 0,
            'access_num'         => $params['access_num'] ?? 0,
            'remind_num'         => $params['remind_num'] ?? 0,
            'itime'              => time(),
            'day_itime'          => strtotime(date('Y-m-d', time())),
            'month_itime'        => strtotime(date('Y-m', time())),
            'utime'              => time(),
            'soure_updatetime'   => 0,
            'deal_time'          => 0,
            'bid_count'          => 0,
            'auction_status'     => $params['auction_status'],
            'source_url'         => $params['source_url'],
        ];
        $auctionId = Db::name('house_auction')->insertGetId($aucData);
        if (!$auctionId) {
            Db::rollback();
            Err::add('添加失败', RespCode::QUERY_ERR);
            return false;
        }
        $res = Db::name('house')->where('id', $house_id)->update(['auction_id' => $auctionId]);
        if (!$res) {
            Db::rollback();
            Err::add('添加失败', RespCode::QUERY_ERR);
        }

        Db::commit();
        return true;
    }

    /**
     * 首页统计
     * @param $params
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function statistics($params) {
        $city_code = $params['city_code'];
        $region_data = Db::name('region')->where('city_code', $city_code)->find();
        $codes = $region_data['p_codes'] . $city_code . ',';
        $map[] = ['h.city_codes', 'like', trim($codes) . '%'];
        $map[] = ['h.deleted', '=', 0];
        //上架房源总数
        $total = Db::name('house')
            ->alias('h')
            ->leftJoin('house_auction ha', 'ha.id=h.auction_id')
            ->where($map)
            ->where('ha.type', 'in', [0, 1, 2, 3, 4, 5, 6])
            ->where('h.is_shelf', 1)
            ->where('h.is_update', 1)
            ->count();
        //抓取房源总数
        $catch = Db::name('house')
            ->alias('h')
            ->leftJoin('house_auction ha', 'ha.id=h.auction_id')
            ->where('ha.type', 'in', [0, 1, 2, 3, 4, 5, 6])
            ->where($map)
            ->where('h.from', 1)
            ->count();
        //已补录
        $bulu = Db::name('house')
            ->alias('h')
            ->leftJoin('house_auction ha', 'ha.id=h.auction_id')
            ->where('ha.type', 'in', [0, 1, 2, 3, 4, 5, 6])
            ->where($map)
            ->where('h.is_update', 1)
            ->count();
        //下架
        $offShelf = Db::name('house')
            ->alias('h')
            ->leftJoin('house_auction ha', 'ha.id=h.auction_id')
            ->where('ha.type', 'in', [0, 1, 2, 3, 4, 5, 6])
            ->where($map)
            ->where('h.is_shelf', 0)
            ->where('h.is_update', 1)
            ->count();
        //待补录
        $daibulu = Db::name('house')
            ->alias('h')
            ->leftJoin('house_auction ha', 'ha.id=h.auction_id')
            ->where('ha.type', 'in', [0, 1, 2, 3, 4, 5, 6])
            ->where($map)
            ->where('h.is_update', 0)
            ->where('h.is_shelf', 0)
            ->count();
        //未处理纠错
        $daijiucuo = Db::name('house')
            ->alias('h')
            ->leftJoin('house_auction ha', 'ha.id=h.auction_id')
            ->where('ha.type', 'in', [0, 1, 2, 3, 4, 5, 6])
            ->where('h.city_codes', 'like', trim($codes) . '%')
            ->where('h.is_update', 1)
            ->where('h.deleted', 0)
            ->whereRaw("(" . Db::name('house_err')
                    ->where('house_id', 'h.id')
                    ->where('status', 0)
                    ->fetchSql(true)
                    ->count() . ") > 0")
            ->count();
        //待补漏
        $daibulou = Db::name('house_traps')
            ->where('status', 0)
            ->count();
        //补录统计图
        date_default_timezone_set('PRC');
        $date1 = self::getDateFromRange($params['start_time1'], $params['end_time1']);
        foreach ($date1 as $k1 => $v1) {
            $buluLine[$k1]['num'] = Db::name('house')
                ->alias('h')
                ->leftJoin('house_auction ha', 'ha.id=h.auction_id')
                ->where('ha.type', 'in', [0, 1, 2, 3, 4, 5, 6])
                ->where('h.bulu_time', strtotime($v1))
                ->where($map)
                ->count();
            $buluLine[$k1]['date'] = date('m-d', strtotime($v1));
        }

        //抓取统计
        $date2 = self::getDateFromRange($params['start_time2'], $params['end_time2']);
        foreach ($date2 as $k2 => $v2) {
            $jd_num = Db::name('house')
                ->alias('h')
                ->leftJoin('house_auction ha', 'ha.id=h.auction_id')
                ->where('ha.type', 'in', [0, 1, 2, 3, 4, 5, 6])
                ->where('h.itime', '>', strtotime($v2 . '00:00:00'))
                ->where('h.itime', '<', strtotime($v2 . '23:59:59'))
                ->where($map)
                ->where('h.source_type', 1)
                ->count();
            $ali_num = Db::name('house')
                ->alias('h')
                ->leftJoin('house_auction ha', 'ha.id=h.auction_id')
                ->where('ha.type', 'in', [0, 1, 2, 3, 4, 5, 6])
                ->where('h.itime', '>', strtotime($v2 . '00:00:00'))
                ->where('h.itime', '<', strtotime($v2 . '23:59:59'))
                ->where($map)
                ->where('h.source_type', 2)
                ->count();
            $jdLine[$k2] = $jd_num;
            $aliLine[$k2] = $ali_num;
            $catchLine_date[$k2] = date('m-d', strtotime($v2));
        }

        return [
            $total,
            $catch,
            $bulu,
            $offShelf,
            $daibulu,
            $daijiucuo,
            $daibulou,
            $buluLine,
            $jdLine,
            $aliLine,
            $catchLine_date,
        ];
    }

    /**
     * 输出日期段的每天日期
     * @param $startdate
     * @param $enddate
     * @return array
     */
    public static function getDateFromRange($startdate, $enddate) {
        date_default_timezone_set('PRC');
        $stimestamp = strtotime($startdate);
        $etimestamp = strtotime($enddate);
        // 计算日期段内有多少天
        $days = ($etimestamp - $stimestamp) / 86400 + 1;
        // 保存每天日期
        $date = array();
        for ($i = 0; $i < $days; $i++) {
            $date[] = date('Y-m-d', $stimestamp + (86400 * $i));
        }
        return $date;
    }

    /**
     * 预览房源
     * @param $map
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function previewHouse($map, $city_codes_str) {
        $data = db("house")
            ->alias('h')
            ->leftJoin('house_village hv', 'hv.id = h.village_id')
            ->leftJoin('house_auction ha', 'h.auction_id = ha.id')
            ->where($map)
            ->orderRaw("field(h.city_code,$city_codes_str)")
            ->field('h.id,hv.name as hv_name,h.title,h.build_time,h.floor,h.renovation_type,h.livingroom,h.bedroom,h.build_area,ha.initial_price,ha.market_price,ha.discount,ha.type,ha.start_time,ha.end_time,h.area,ha.final_price')
            ->select();
        foreach ($data as &$val) {
            if ($val['discount'] <= 1 && $val['discount'] != -1) {
                $discount = '低于1折';
            } elseif ($val['discount'] == -1) {
                $discount = '- -';
            } else {
                $discount = $val['discount'];
            }
            $arr = [
                'hv_name'         => empty($val['hv_name']) ? '' : $val['hv_name'],
                'title'           => $val['title'],
                'build_time'      => $val['build_time'],
                'floor'           => $val['floor'],
                'renovation_type' => self::RENOVATION_TYPE[$val['renovation_type']],
                'livingroom'      => $val['livingroom'],
                'bedroom'         => $val['bedroom'],
                'build_area'      => deal_data_info($val['build_area'], 4),
                'initial_price'   => deal_data_info($val['initial_price'], 6),
                'market_price'    => deal_data_info($val['market_price'], 6),
                'final_price'     => deal_data_info($val['final_price'], 6),
                'discount'        => $discount,
                'type'            => self::A_TYPES[$val['type']],
                'start_time'      => date('m月-d日', $val['start_time']),
                'end_time'        => date('m月-d日', $val['end_time']),
            ];
            $tree[$val['area']]['area'] = $val['area'];
            $tree[$val['area']]['children'][] = $arr;
            for ($index1 = 0; $index1 < count($tree[$val['area']]['children']); $index1++) {
                $tree[$val['area']]['children'][$index1]['id'] = $index1 + 1;
            }
        }
        $res = array_values($tree);
        return $res;
    }


    public static function getExportDatas($map, $whereRaw, $column, $order) {

        $data = db('house')
            ->alias('h')
            ->leftJoin('house_village hv', 'hv.id=h.village_id')
            ->leftJoin('house_auction ha', 'ha.id=h.auction_id')
            ->leftJoin('house_type ht', 'ht.id=h.house_type_id')
            ->leftJoin('business_area hb', 'hb.id=h.business_area_id')
            ->where($map);
        if ($whereRaw) {
            $data->whereRaw($whereRaw);
        }
        $data = $data->order($order)
            ->field($column)
            ->select();

        return $data;
    }

    /**
     * 房源导出数据处理
     * @param $data
     * @param $field
     */
    public static function hanldReturnDwnlaod($data, $field) {
        foreach ($data as $key => $value) {
            if (in_array('house_cate', $field)) {
                //房屋类型二级
                $data[$key]['house_cate'] = config('export.house_cate')[$value['house_cate']];
            }
            if (in_array('property_type', $field)) {
                //产权类型
                $data[$key]['property_type'] = $value['property_type'] ? config('export.property_type')[$value['property_type']] : '未知';
            }
            if (in_array('door_model', $field)) {
                $door = $value['door_model'] ? explode('-', $value['door_model']) : [];
                //户型
                $data[$key]['door_model'] = $door[0] ? $door[0] . '室' . $door[1] . '厅' : '';
            }
            if (in_array('build_area', $field)) {
                //建筑面积
                $data[$key]['build_area'] = $value['build_area'] ? deal_area_list($value['build_area'], 4) : 0;
            }
            if (in_array('renovation_type', $field)) {
                //装修
                $data[$key]['renovation_type'] = config('export.renovation_type')[$value['renovation_type']];
            }
            if (in_array('living_type', $field)) {
                //居住情况
                $data[$key]['living_type'] = config('export.living_type')[$value['living_type']];
            }
            if (in_array('auction_status', $field)) {
                //拍卖状态
                $data[$key]['auction_status'] = config('export.auction_status')[$value['auction_status']];
            }
            if (in_array('start_time', $field)) {
                //拍卖开始时间
                $data[$key]['start_time'] = $value['start_time'] ? date('Y/m/d H:i:s', $value['start_time']) : '';
            }
            if (in_array('end_time', $field)) {
                //拍卖结束时间
                $data[$key]['end_time'] = $value['end_time'] ? date('Y/m/d H:i:s', $value['end_time']) : '';
            }
            if (in_array('pay_selloff', $field)) {
                //变卖预交款
                $data[$key]['pay_selloff'] = $value['pay_selloff'] ? export_money_info($value['pay_selloff']) : 0;
            }
            if (in_array('initial_price', $field)) {
                //起拍价
                $data[$key]['initial_price'] = $value['initial_price'] ? export_money_info($value['initial_price']) : 0;
            }
            if (in_array('consult_price', $field)) {
                //法院评估价
                $data[$key]['consult_price'] = $value['consult_price'] ? export_money_info($value['consult_price']) : 0;
            }
            if (in_array('market_price', $field)) {
                //市场评估价
                $data[$key]['market_price'] = $value['market_price'] ? export_money_info($value['market_price']) : 0;
            }
            if (in_array('final_price', $field)) {
                //成交价
                $data[$key]['final_price'] = $value['final_price'] ? export_money_info($value['final_price']) : 0;
            }
            if (in_array('anjuke_price', $field)) {
                //安居客成交单价
                $data[$key]['anjuke_price'] = $value['anjuke_price'] ? export_money_info($value['anjuke_price']) : 0;
            }
            if (in_array('lifts', $field)) {
                //楼梯类型
                $data[$key]['lifts'] = $value['lifts'] ? config('export.lifts')[$value['lifts']] : '未知';
            }
            if (in_array('discount', $field)) {
                //折扣比
                if ($value['discount'] <= 1 && $value['discount'] != -1) {
                    $data[$key]['discount'] = "低于1折";
                } elseif ($value['discount'] == -1) {
                    $data[$key]['discount'] = "- -";
                } else {
                    $data[$key]['discount'] = $value['discount'];
                }
            }
            if (in_array('type', $field)) {
                //拍卖次数
                $data[$key]['type'] = config('export.auction_type')[$value['type']];
            }

        }

        return $data;

    }

    /**
     * 导出字段
     * @return array
     */
    public static function getExportField() {
        $field = config('export.export_field_name');
        $i = 0;
        foreach ($field as $key => $value) {
            $i++;
            $data[$key]['key'] = $key;
            $data[$key]['value'] = $value;
            $data[$key]['order'] = $i;
        }
        return array_values($data);
    }

    /**
     * 设置重点房源
     * @param $params
     * @return int|string
     * @throws Exception
     * @throws PDOException
     */
    public static function setImportant($params, $im) {
        $model = new self();
        $house = $model->where('id', $params['id'])->findOrEmpty();
        if (empty($house)) {
            Err::add('房源不存在', RespCode::PARAMS_ERR);
            return false;
        }
        //取消
        if ($im == 0) {
            $up = 0;
        }//设置
        else {
            $data = $model->alias('h')
                ->leftJoin('house_auction ha', 'ha.id=h.auction_id')
                ->where('h.id', $params['id'])
                ->field('h.important,ha.auction_status')
                ->find()
                ->toArray();
            if ($data['auction_status'] != 1) {
                Err::add('该房源不是待开始房源', RespCode::PARAMS_ERR);
                return false;
            }
            $up = 1;
        }
        $model
            ->where('id', $params['id'])
            ->update(['important' => $up]);
        return true;
    }
}
